<?php

namespace app\api\controller\bonus;

use think\Config;
use think\Db;

/**
 * 分红数据统计
 */
class Datas
{
	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config = [
		"prefix" 	=> "fd_",
		"detail" 	=> "bonus_details", // 收益明细管理表
		"stands"	=> "bonus_stands",	// 达标计算模板管理表
		"level"		=> "bonus_level",	// 等级管理表
		"cahs"		=> "bonus_cash",	// 分红返现模板
		"upgrade"	=> "bonus_upgrade",	// 达标晋升记录
		"pseudo"	=> "bonus_upgrade_pseudo",	// 分红返现模板
		"user"		=> "user"
	];

	/**
	 * 默认架构方法
	 */
	public function __construct()
	{
	}

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 获取汇总
	 * @param integer $id  代理ID
	 * @return bool|array
	 */
	public function get_total($id)
	{
		$return = ["bonus" => []];
		if (!empty($id)) {
			if ($this->isEmpty($id)) {
				$data = [];
				$data = Db::name($this->config["detail"])
					->where("agid = {$id}")
					->field("lev_code levs,sum(earns) earn_money , sum(trans) tran_money")
					->group("lev_code")
					->select();
				$return["bonus"]["title"] = "分红收益";
				$return["bonus"]["data"] = $data;
			}
		}
		return $return;
	}

	/**
	 * 按年显示-分红达标收益列表
	 * @return array|boolean
	 */
	public function person_years_stands_list($id)
	{
		$years = date("Y");
		if (!empty($id)) {
			$data = [];
			$details = Db::name($this->config["detail"])
				->where("from_unixtime(times, '%Y') = '{$years}' and agid = {$id}")
				->field("agid,times")
				->group("times")
				->select();
			if ($details) {
				foreach ($details as $val) {
					$temp = [];
					$temp = $val;
					$temp["months"] = date("Y-m", $val["times"]);
					$temp["data"] = $this->_months_earns_data($val["agid"], $val["times"]);
					array_push($data, $temp);
				}
			}
			return $data;
		}
		return false;
	}

	/**
	 * 个人 - 按等级月收益
	 * @return array
	 */
	public function _months_earns_data($id, $times)
	{
		return Db::name($this->config["detail"])
			->where("agid = {$id} and times = {$times}")
			->field("lev_code,per_nums,trans,money,earns")
			->select();
	}

	/**
	 * 达标等级列表
	 * 
	 * @return array|bool
	 */
	public function stands_lev_list()
	{
		$data = Db::name($this->config["level"])
			->field("code")
			->where("state = 1")
			->select();
		if ($data) {
			foreach ($data as $key => $value) {
				$data[$key]["condi"] = $this->_stands_template_condi_join($value["code"]);
				$data[$key]["monData"] = $this->_month_stands_lists($value["code"]);
			}
		}
		return $data;
	}

	/**
	 * 按月达标
	 * @return array
	 */
	public function _month_stands_lists($lev_code)
	{
		$data = [];
		$months = $this->_month_array();
		foreach ($months as $vals) {
			$temp = [];
			$temp["levs"] = $lev_code;
			$temp["times"] = date('Y-m', $vals);
			$temp["timesNick"] = $this->_months_nick($vals);
			$temp["money"] = "0.00";
			$temp["nums"] = 0;
			// 本月数据计算
			$temp["nums"] = $this->_month_stands_nums($lev_code, $vals);
			$temp["money"] = $this->_month_bonus_money($lev_code, $vals);
			// 上月数据计算
			if (strtotime("-1 month", strtotime(date("Y-m"))) == $vals) {
					
				if (date('d') <= 15) {
					$temp["nums"] = $this->_month_stands_nums($lev_code, $vals);
					$temp["money"] = $this->_month_bonus_money($lev_code, $vals);
					if (strtotime("2023-10") == $vals) {
						$temp["money"] = 9673.71;
					}
				} else {
					if (strtotime("2023-10") == $vals) {
						$temp["money"] = 9673.71;
					}
					$check = Db::name($this->config["detail"])
						->where("lev_code = '{$lev_code}' and times = {$vals}")
						->count();
					if ($check) {
						$query = Db::name($this->config["detail"])
							->where("lev_code = '{$lev_code}' and times = {$vals}")
							->field("per_nums,money")
							->find();
						$temp["money"] = $query["money"];
						$temp["nums"] = $query["per_nums"];
					}
				}
			}
			array_push($data, $temp);
		}
		return $data;
	}

	/**
	 * 获取本月 可实时达标人数
	 */
	public function _month_stands_nums($lev, $times)
	{

		$con = 0;
		$dbConfig_arrs = Config::get("db");
		if ($dbConfig_arrs) {
			$where = " and times = " . $times;
			if (strtotime(date("Y-m")) == $times) {
				$first_day = strtotime(date("Y-m-01"));
				$ends_day  = strtotime("+1 day", strtotime(date("Y-m-d")));
				$where = " and state = 1 and (createTime >= {$first_day} and createTime < {$ends_day})";
			}
			$table = $this->config["upgrade"];
			foreach ($dbConfig_arrs as $v) {
				$conn = Db::connect($v);
				$isExist = $conn->query("SHOW TABLES like '" . $v["prefix"] . $table . "'");
				if ($isExist) {
					if ($conn) {
						$total = $conn->name($table)->where("lev_code = '{$lev}'" . $where)->count();
						$con += $total;
					}
				}
			}
		}
		return $con;
	}

	/**
	 * 获取本月 可实时分红金额 
	 */
	public function _month_bonus_money($lev, $times)
	{
		$money = "0.00";
		$dbConfig_arrs = Config::get("db");
		if ($dbConfig_arrs) {
			$ratio = $this->_cash_ratio($lev);
			$table = "bonus_calc_trans_" . date("Y", $times);
			foreach ($dbConfig_arrs as $k => $v) {
				$conn = Db::connect($v);
				$isExist = $conn->query("SHOW TABLES like '" . $v["prefix"] . $table . "'");
				if ($isExist) {
					if ($conn) {
						$total = $conn->name($table)->where("times = {$times}")->sum("transAmt");
						if ($total) {
							// 实际达标人数
							// z / s
							// $multi = $this->_stands_reals_nums($lev, $times);
							$multi = 5;
							// $multi = \app\ports\constants\BonusConstants::CALC_BONUS_MULTI;
							// 平均值
							$bonus_money = $this->_base_calc_bonus($total, $ratio, $multi);
							if($times == strtotime("2023-11")){
								$bonus_money -= 558.78;
							}
							// // 达标数
							// $stands_nums = $this->_stands_all_nums($lev, $times);
							// // 返现金额
							// $cash = $this->_base_calc_cash($argv, $stands_nums);
							$money += $bonus_money;
						}
					}
				}
			}
		}
		return round($money, 2);
	}

	/**
	 * 平均值计算
	 */
	public function _base_calc_bonus($sum, $ratio, $multi)
	{
		// return  bcdiv(bcmul((string) $sum, bcdiv((string)$ratio, "10000", 6), 2), (string)$multi);
		return bcmul(bcmul((string)$sum, (string) $multi), bcdiv((string)$ratio, "10000", 6), 2);
	}

	/**
	 * 全部标数
	 */
	public function _stands_all_nums($lev, $times)
	{
		$con = 1;
		if ($con && $times) {
			$where = " and times = " . $times;
			if (strtotime(date("Y-m")) == $times) {
				$first_day = strtotime(date("Y-m-01"));
				$ends_day  = strtotime("+1 day", strtotime(date("Y-m-d")));
				$where = " and (createTime >= {$first_day} and createTime < {$ends_day})";
			}
			$check = Db::name($this->config["upgrade"])
				->where("lev_code = '{$lev}'" . $where)
				->count();
			if ($check) {
				$con = $check;
			}
		}
		return $con;
	}

	/**
	 * 实际达标数
	 */
	public function _stands_reals_nums($lev, $times)
	{
		$con = 1;
		if ($con && $times) {
			$check = Db::name($this->config["upgrade"])
				->where("lev_code = '{$lev}' and times = {$times} and isReals = 1")
				->count();
			if ($check) {
				$con = $check;
			}
		}
		return $con;
	}

	/**
	 * 返现值计算
	 */
	public function _base_calc_cash($argv, $multi)
	{
		return  bcmul((string)$argv, (string)$multi, 2);
	}

	/**
	 * 平均值计算
	 */
	public function _base_calc_argv($sum, $ratio, $multi)
	{
		return  bcdiv(bcmul((string) $sum, bcdiv((string)$ratio, "10000", 6), 2), (string)$multi);
	}

	/**
	 * 分红比率
	 */
	public function _cash_ratio($lev_code)
	{
		$lev_id = Db::name($this->config["level"])->where("code = '{$lev_code}'")->value("id");
		return Db::name($this->config["cahs"])->where("lev_id = {$lev_id}")->value("radio");
	}

	/**
	 * 月份昵称
	 */
	public function _months_nick($times)
	{
		$now = strtotime(date("Y-m", time()));
		return ($now == $times ? "本月" : "上月");
	}

	/**
	 * 达标详情
	 * @return array
	 */
	public function stands_details($levs, $times)
	{
		$data = [];
		$conn_db_arr = \think\Config::get("db");
		if ($conn_db_arr) {
			foreach ($conn_db_arr as $dbConfig) {
				$connect = Db::connect($dbConfig);
				if ($connect) {
					$chang = strtotime("2023-10");
					$times = strtotime($times);
					$where = " and times = " . $times;
					if (strtotime(date("Y-m")) == $times) {
						$first_day = strtotime(date("Y-m-01"));
						$ends_day  = strtotime("+1 day", strtotime(date("Y-m-d")));
						$where = " and state = 1 and  (createTime >= {$first_day} and createTime < {$ends_day})";
					}
					$query = $connect->table($dbConfig["prefix"] . $this->config["upgrade"])
						->where("lev_code = '{$levs}'" . $where)
						->field("agid,isReals,from_unixtime(times, '%Y-%m') dates")->select();
					if ($query) {
						foreach ($query as $key => $va) {
							if ($va["isReals"] == 2) {
								$res =  $connect->table($dbConfig["prefix"] . $this->config["pseudo"])->where("id = " . $va["agid"])->value("insert(phone , 4 , 4 , '****')");
								if ($res) {
									$query[$key]["phone"] = $res;
								} else {
									$query[$key]["phone"] = $connect->table($dbConfig["prefix"] . $this->config["user"])->where("id = " . $va["agid"])->value("insert(mobile , 4 , 4 , '****')");
									if($times <= $chang){
										if($va["agid"] == 213){
											// 19990763152
											$query[$key]["phone"] = "199****3152";
										}
									}
									
								}
							}
							if ($va["isReals"] == 1) {
								$query[$key]["phone"] = $connect->table($dbConfig["prefix"] . $this->config["user"])->where("id = " . $va["agid"])->value("insert(mobile , 4 , 4 , '****')");
							}
						}
						$data = array_merge($data, $query);
					}
				}
			}
		}
		return $data;
	}

	/**
	 * 日期
	 * @return array
	 */
	public function _month_array()
	{
		$syue = date("m", time());
		$ssyue = (int)$syue - 1;
		// $ssyue = (int)$syue;
		$months =  [];
		for ($i = $ssyue; $i <= (int)$syue; $i++) {
			$months[] = mktime(0, 0, 0, $i, 1);
		}
		rsort($months);
		return $months;
	}

	/**
	 * 分红达标条件 拼接字符串
	 * @return string
	 */
	public function _stands_template_condi_join($lev_code)
	{
		$lev_id = Db::name($this->config["level"])->where("code = '{$lev_code}'")->value("id");
		return Db::name($this->config["stands"])->where("lev_id = {$lev_id}")->value("concat(nums,' * ' , tranAmt )");
	}

	/**
	 * 查看信息
	 */
	public function isEmpty($id = 0)
	{
		$where = (!empty($id) ? "agid = {$id}" : "");
		$count = Db::name($this->config["detail"])
			->where($where)
			->count();
		return $count;
	}
}
